public class AutoNumberHelper
{
	public enum AutoNumberType {AccountAgencyID, AccountMasterClientID}
	
	private List<sobject> objects; 
	private string fieldName;
	private string utilObjectName;
	private AutoNumberType numberType;
	
	// Constructor
	// Parameters:
	// 	numberType - The type of auto number you want (this determines the object type and field that will be populated
	//               and auto number utility object that will be used)
	public AutoNumberHelper(AutoNumberType numberType){
		this.numberType = numberType;
		
		if(numberType == AutoNumberType.AccountAgencyID){
			utilObjectName = 'Util_Account_Agency_ID_AutoNumber__c';
			fieldName = 'Agency_ID__c';			
		}

		if(numberType == AutoNumberType.AccountMasterClientID){
			utilObjectName = 'Util_Account_Master_Client_AutoNumber__c';
			fieldName = 'Master_Client_ID__c';			
		}
		
		objects = new List<sobject>();
	}	
	
	// PrepareAutoNumber - Sets up an object to get an autonumber population (but only populates after 'Populate()' is called')
	// Parameters:
	// 	obj - The object that will have it's autonumber field populated
	public void PrepareAutoNumber(sobject obj){
		objects.add(obj);
	}
	
	// Populate - Populates the objects with auto numbers
	// Notes: This invokes some DML and SOQL statements so should only be called once per transaction 
	public void Populate(){
		integer numObjects = objects.size();
		
		if(numObjects > 0){
			List<sobject> utilObjs = InstantiateUtilObjects(numObjects);		
			insert utilObjs;
			
			Set<ID> idset = new Set<ID>();
			for(sobject obj : utilObjs)
				idset.add(obj.id);
			
			string query = 'Select Name from ' + utilObjectName + ' where ID in :idset'; 
			utilObjs = Database.Query(query);
			
			for(integer i=0; i < numObjects; i++)
			{
				objects[i].put(fieldName, utilObjs[i].get('Name'));
			}
			delete utilObjs;
		}
	}
	
	public List<sObject> GetPopulatedObjects(){
		return objects;
	}
	
	private List<sobject> InstantiateUtilObjects(integer numberOfObjects){
		List<sobject> utilObjs = new sobject[numberOfObjects];
		
		for(integer i=0; i < numberOfObjects; i++){
		
			if(numberType == AutoNumberType.AccountAgencyID)
				utilObjs[i] = new Util_Account_Agency_ID_AutoNumber__c();
		
			if(numberType == AutoNumberType.AccountMasterClientID)
				utilObjs[i] = new Util_Account_Master_Client_AutoNumber__c();
		}		
		return utilObjs;
	}
}